<template>
  <view class="page">
    <!-- 顶部导航 -->
    <!-- <view class="header">
      <image 
        class="back-btn" 
        src="/static/img/icon-Get-into@3.png" 
        @click="goBack"
      ></image>
      <view class="header-title">
        <text>原手机号</text>
      </view>
    </view> -->
    
    <!-- 内容区域 -->
    <view class="wrapper">
      <view class="change">
        <view class="cont">
          <!-- 手机号输入框 -->
          <view class="input-item">
            <image 
              class="input-icon" 
              :src="serverAddress+'img/login/icon-iphone@2x.png'"
            ></image>
            <input 
              class="input-field"
              type="number"
              v-model="phoneNumber"
              maxlength="11"
              readonly
              placeholder="请输入手机号"
            />
          </view>
          
          <!-- 验证码输入框 -->
          <view class="input-item">
            <image 
              class="input-icon code-icon" 
              :src="serverAddress+'/img/login/icon-xinxi@2x.png'"
            ></image>
            <input 
              class="input-field"
              type="number"
              v-model="verifyCode"
              placeholder="短信验证码"
            />
            <button 
              class="verify-btn"
              :class="{ disabled: countDown > 0 }"
              @click="sendVerifyCode"
              :disabled="countDown > 0"
            >
              {{ countDown > 0 ? `${countDown} 秒后重发` : '发送验证码' }}
            </button>
          </view>
        </view>
        
        <!-- 下一步按钮 -->
        <button class="next-btn" :style="{'backgroundImage': `url(${serverAddress}img/login/Button-@2x.png)`}" @click="nextStep">下一步</button>
      </view>
    </view>
  </view>
</template>

<script>
import { userApi } from '@/api/index.js'
import { getCurrentUser } from '@/api/auth.js'
import {
		inject
	} from 'vue'
export default {
  data() {
    return {
		serverAddress: inject('$serverAddress'),
      phoneNumber: '', // 手机号
      verifyCode: '', // 验证码
      countDown: 0, // 倒计时
      timer: null, // 定时器
      ip: '' // IP地址
    }
  },
  
  onLoad() {
    this.initPhoneNumber()
    this.getIpAddress()
  },
  
  onUnload() {
    // 清除定时器
    if (this.timer) {
      clearInterval(this.timer)
    }
  },
  
  methods: {
    // 初始化手机号
    initPhoneNumber() {
      try {
        // 优先从本地存储获取新手机号
        const newPhone = uni.getStorageSync('newPhone')
        if (newPhone) {
          this.phoneNumber = newPhone
        } else {
          // 从用户信息获取当前手机号
          const userInfo = getCurrentUser()
          if (userInfo && userInfo.phone) {
            this.phoneNumber = userInfo.phone
          }
        }
      } catch (e) {
        console.error('获取手机号失败:', e)
      }
    },
    
    // 获取IP地址
    async getIpAddress() {
      try {
        const res = await userApi.getIp()
        if (res && res.data) {
          this.ip = res.data
        }
      } catch (error) {
        console.error('获取IP地址失败:', error)
        this.ip = '0.0.0.0'
      }
    },
    
    // 发送验证码
    async sendVerifyCode() {
      // 验证手机号
      if (!this.phoneNumber) {
        uni.showToast({
          title: '手机号不能为空',
          icon: 'none',
          duration: 1500
        })
        return
      }
      
      const phoneReg = /^1[0-9]\d{9}$/
      if (!phoneReg.test(this.phoneNumber)) {
        uni.showToast({
          title: '手机号格式错误',
          icon: 'none',
          duration: 1500
        })
        return
      }
      
      try {
        // 检查手机号是否已注册
        const checkRes = await userApi.checkMobile({
          mobile: this.phoneNumber
        })
        
        if (checkRes && checkRes.data && checkRes.data.is_used) {
          // 发送验证码
          const sendRes = await userApi.sendMobileCodeForChange({
            mobile: this.phoneNumber,
            last_login_ip: this.ip
          })
          
          if (sendRes && !sendRes.r) {
            uni.showToast({
              title: '发送验证码成功',
              icon: 'success',
              duration: 1500
            })
            this.startCountDown()
          } else {
            uni.showToast({
              title: sendRes.msg || '发送验证码失败',
              icon: 'none',
              duration: 1500
            })
          }
        } else {
          uni.showToast({
            title: '手机号已注册',
            icon: 'none',
            duration: 1500
          })
        }
      } catch (error) {
        console.error('发送验证码失败:', error)
        uni.showToast({
          title: '发送验证码失败',
          icon: 'none',
          duration: 1500
        })
      }
    },
    
    // 开始倒计时
    startCountDown() {
      this.countDown = 60
      this.timer = setInterval(() => {
        this.countDown--
        if (this.countDown <= 0) {
          clearInterval(this.timer)
          this.timer = null
        }
      }, 1000)
    },
    
    // 下一步验证
    async nextStep() {
      if (!this.verifyCode) {
        uni.showToast({
          title: '请输入验证码',
          icon: 'none',
          duration: 1500
        })
        return
      }
      
      try {
        const res = await userApi.checkMobileCode({
          mobile: this.phoneNumber,
          code: this.verifyCode,
          last_login_ip: this.ip
        })
        
        if (res && res.r === 0) {
          uni.showToast({
            title: res.msg || '验证成功',
            icon: 'success',
            duration: 1500
          })
          
          // 跳转到设置新手机号页面
          setTimeout(() => {
            uni.navigateTo({
              url: '/pages/my/set-loginphonen'
            })
          }, 1500)
        } else {
          uni.showToast({
            title: res.msg || '验证码错误',
            icon: 'none',
            duration: 1500
          })
        }
      } catch (error) {
        console.error('验证码验证失败:', error)
        uni.showToast({
          title: '验证失败，请重试',
          icon: 'none',
          duration: 1500
        })
      }
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss" scoped>
.page {
  width: 100%;
  min-height: 100vh;
  background-color: #F6F6F6;
}

.header {
  position: relative;
  width: 100%;
  height: 84rpx;
  line-height: 84rpx;
  padding: 0 28rpx;
  background-color: #FFFFFF;
  font-size: 38rpx;
  color: #656565;
  border-bottom: 1rpx solid #E6E6E6;
  box-sizing: border-box;
  
  .header-title {
    width: 100%;
    text-align: center;
    height: 84rpx;
    line-height: 84rpx;
  }
  
  .back-btn {
    position: absolute;
    left: 28rpx;
    top: 22rpx;
    width: 24rpx;
    height: 38rpx;
  }
}

.wrapper {
  padding: 30rpx;
}

.change {
  width: 100%;
}

.cont {
  width: 100%;
  margin-top: 30rpx;
}

.input-item {
  position: relative;
  width: 690rpx;
  height: 98rpx;
  border-radius: 4rpx;
  background-color: white;
  border: 1rpx solid #F0F0F0;
  margin: 0 auto 32rpx auto;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .input-icon {
    position: absolute;
    left: 32rpx;
    top: 24rpx;
    width: 34rpx;
    height: 34rpx;
    z-index: 1;
    
    &.code-icon {
      top: 34rpx;
      width: 38rpx;
      height: 30rpx;
    }
  }
  
  .input-field {
    position: absolute;
    border: 0;
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    padding-left: 84rpx;
    padding-right: 160rpx;
    font-size: 32rpx;
    background-color: white;
  }
  
  .verify-btn {
    position: absolute;
    right: 26rpx;
    top: 22rpx;
    padding: 0 14rpx;
    height: 57rpx;
    line-height: 57rpx;
    border: 1rpx solid #37A962;
    color: #37A962;
    font-size: 32rpx;
    border-radius: 4rpx;
    background-color: white;
    
    &.disabled {
      background-color: #f5f5f5;
      color: #999;
      border-color: #d9d9d9;
    }
  }
}

.next-btn {
  // width: 690rpx;
  height: 104rpx;
  border: 0;
  border-radius: 10rpx;
  overflow: hidden;
  margin: 28rpx 30rpx;
  color: white;
  font-size: 38rpx;
  // background: linear-gradient(135deg, #37A962 0%, #2E8A51 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  &:active {
    opacity: 0.8;
  }
}
</style>